package logic

import (
	"common/global"
	"common/model"
	"common/pkg"
	"context"
	"errors"
	"fmt"
	"strings"
	user "user_server/proto"
)

func (s *UserServer) UserRealName(ctx context.Context, req *user.UserRealNameReq) (*user.UserRealNameResp, error) {
	verify := pkg.IdCardVerify(req.CardId)
	if !verify {
		return &user.UserRealNameResp{
			Success: "身份验证不正确",
		}, nil
	}
	var o model.User
	id, err := o.QueryUserRealNameCardId(req.CardId)
	if id {
		return &user.UserRealNameResp{}, errors.New("身份证号已被使用")
	}
	uid, err := o.GetUserAccountInfoByUid(req.UserId)
	if err != nil {
		return &user.UserRealNameResp{}, errors.New("用户不存在")
	}
	if uid.RealName != "" || uid.CardId != "" {
		return &user.UserRealNameResp{}, errors.New("用户已实名")
	}
	req.RealName = strings.TrimSpace(req.RealName) // 去除空格
	req.CardId = strings.ToUpper(req.CardId)
	pkg.RealName(req.CardId, req.RealName)
	fmt.Println(req.CardId)
	fmt.Println(req.RealName)

	tx := global.Db.Begin()
	err = tx.Model(&model.User{}).
		Where("id = ?", req.UserId).
		Updates(map[string]interface{}{
			"real_name": req.RealName,
			"card_id":   req.CardId,
		}).Error
	if err != nil {
		tx.Rollback()
	}
	tx.Commit()
	return &user.UserRealNameResp{
		Success: "实名成功",
	}, nil
}
